package com.app.util.common;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class SysConfig {

	private static Map<String, String> configMap;
	
	
	@Value("${sysConfig.sysConfigFilePath}")
	String sysConfigFilePath;
	
	private static  String filePath;
	
	@PostConstruct
    public void init() {
		filePath = sysConfigFilePath;		
    }
	
	public static void loadProperty() {
		if (configMap == null) {
			configMap = new HashMap<String, String>();
		} else {
			configMap.clear();
		}
		try {
			if(filePath == null) {
				filePath = "";
			}
			filePath = filePath.replace("classpath:", PathUtil.getClassResources());
			
			InputStream is = new FileInputStream(filePath);
			BufferedReader bf = new BufferedReader(new  InputStreamReader(is, "UTF-8"));
			Properties prop = new Properties();
			prop.load(bf);
			if (prop != null) {
				Enumeration<?> eProps = prop.propertyNames();
				while (eProps.hasMoreElements()) {
					String strTempr = (String) eProps.nextElement();
					String strPropValue = prop.getProperty(strTempr);
					configMap.put(strTempr, strPropValue);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取配置文件指定属性值
	 * @param key
	 * @return
	 */
	public static String getProString(String key) {
		if (configMap == null) {
			loadProperty();
		}
		return configMap.get(key);
	}
	
	/**
	 * 获取配置文件指定属性值
	 * @param key
	 * @return
	 */
	public static boolean getProBoolan(String key){
		String result = getProString(key);
		if(result == null ) {
			return false;
		}
		if("true".equals(result.toLowerCase())){
			return true;
		}else{
			return false;
		}
	}
	
	/**
	 * 获取配置文件指定属性值
	 * @param key
	 * @return
	 */
	public static Integer getProInt(String key){
		String result = getProString(key);
		try{
			return Integer.valueOf(result);
		}catch (Exception e) {
			return null;
		}
	}
	/**
	 * 清除记录
	 */
	public static void clear(){
		configMap = null;
	}
}
